// 提供两个方法，一个是代理的，一个是绑定的

function proxyApi(apiDefs, axios) {
    for (let key in apiDefs) {
        let def = apiDefs[key];

        if (typeof (def) !== 'function') {
            throw "not surport proxy this object";
        }

        let { method, path } = def;

        console.log(`proxy ${path}`, def)
        apiDefs[key] = new Proxy(def, {
            apply: (target, thisArg, argArray) => {
                return new Promise(async (resolve, reject) => {
                    try {
                        let res = await axios.request({
                            method: method ? method : 'POST',
                            url: path
                        })

                        resolve(res.data);
                    } catch (error) {
                        reject("call server error:" + error.toString());
                    }
                })
            }
        })
    }
}

function bindExpress(def, expressApp, callback) {
    console.log(def);
    let { method, path } = def;
    let methodLow = method ? method.toLowerCase() : 'all';
    expressApp[methodLow](path, callback);
}

module.exports = {
    proxyApi,
    bindExpress
}